package com.code2roc.fastboot.listener;

import com.code2roc.fastboot.framework.util.FileUtil;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.net.URLDecoder;

@Component
public class StaticResourceFileListener implements FileAlterationListener {
    private String monitorDir;
    private String copyToDir;

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {
        if(StringUtil.isEmpty(monitorDir)){
            monitorDir = fileAlterationObserver.getDirectory().getAbsolutePath();
            try{
                if(monitorDir.contains("public")){
                    copyToDir =  URLDecoder.decode(ResourceUtils.getURL("classpath:public").getPath());
                }else if(monitorDir.contains("static")){
                    copyToDir =  URLDecoder.decode(ResourceUtils.getURL("classpath:static").getPath());
                }
            }catch (Exception e){

            }
        }
    }

    @Override
    public void onDirectoryCreate(File file) {
        snycFolder();
    }

    @Override
    public void onDirectoryChange(File file) {
        snycFolder();
    }

    @Override
    public void onDirectoryDelete(File file) {
        snycFolder();
    }

    @Override
    public void onFileCreate(File file) {
        snycFolder();
    }

    @Override
    public void onFileChange(File file) {
        snycFolder();
    }

    @Override
    public void onFileDelete(File file) {
        snycFolder();
    }

    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {

    }

    private void snycFolder(){
        if(!StringUtil.isEmpty(monitorDir) && !StringUtil.isEmpty(copyToDir)){
            try{
                FileUtil.copyFileFolder(monitorDir,copyToDir);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

